package com.cysion.study.ui.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.cysion.other.color
import com.cysion.other.startActivity_ex
import com.cysion.study.R
import com.cysion.study.adapter.PTeacherFragmentAdapter
import com.cysion.study.entity.FamilyeduAppointEntity
import com.cysion.study.entity.UserEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseFragment
import com.cysion.study.ktbox.base.ITEM_CLICK
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.ui.NoticeActivity
import com.cysion.study.ui.login.LoginActivity
import com.cysion.study.ui.pteacher.PCourseDetailActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.targetfun._subscribe
import com.scwang.smartrefresh.layout.constant.RefreshState
import kotlinx.android.synthetic.main.fragment_p_teacher.*

/**
 * 家教新首页
 * Created by chu on 2019-06-30.
 */
class PTeacherFragment:BaseFragment(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.fragment_p_teacher
    }

    override fun initView() {
        activity!!.darkTextTheme(activity!!.color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            initElements(TopBar.ELEMENT.HIDE,TopBar.ELEMENT.TEXT,TopBar.ELEMENT.IMG)
            setTitle("牛课工场家教")
            setTitleColor(color(R.color.black))
            setRightImg(R.mipmap.icon_notification)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.RIGHT) {//通知
                    UIHelper.jump(activity,NoticeActivity::class.java)
                }
            }
        }
        initRecyclerView()
        initRefreshLayout()
        tv_perfect.setOnClickListener(this)
        getUserInfos()

        tb_onoff.setOnClickListener(this)
        /*tb_onoff.setOnToggleChanged {
            setIfJiajiao(it)
        }*/
    }

    override fun visibleAgain() {
        super.visibleAgain()
        CLog.i("visibleAgain中的token=" + UserCache.userInfo?.nickName)
        var userBean=UserCache.userInfo
        if (userBean != null) {
            updateTeacherStatus()
        } else {
            getUserInfos()
        }
    }

    private fun updateTeacherStatus() {
        //ifFmleduInfo":"",//家教信息是否完善：0、代表未完善；1、代表已完善
        var ifFmleduInfo = UserCache.userInfo?.ifFmleduInfo
        if (ifFmleduInfo == "0") {
            ll_family_info.visibility = View.VISIBLE
        } else if (ifFmleduInfo == "1") {
            ll_family_info.visibility = View.GONE
        } else {
            ll_family_info.visibility = View.GONE
        }
        //ifJiajiao":"",//家教中是否招募学生：0、代表不招募；1、代表招聘
        var ifJiajiao = UserCache.userInfo?.ifJiajiao
        CLog.i("首页=$ifJiajiao")
        if (ifJiajiao == "0") {
            tb_onoff.toggleOff()
        } else if (ifJiajiao == "1") {
            tb_onoff.toggleOn()
        }

    }

    private fun getUserInfos() {
        ApiClient.api.getTeacherInfos(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    if (!TextUtils.isEmpty(it.id)) {
                        UserCache.save(it)
                        println("###首页页面开关="+it.ifJiajiao)
                        UserCache.userInfo = it
                        updateTeacherStatus()
                    }
                }
            }
    }
    private lateinit var mAdapter: PTeacherFragmentAdapter
    private val dataList: MutableList<FamilyeduAppointEntity> = mutableListOf()
    private var curPage = 1

    override fun initData() {
        super.initData()
        smartLayout.autoRefresh()
    }

    override fun onResume() {
        super.onResume()
        curPage = 1
        getDataList()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        println("#####登录返回")
        if (requestCode == 103 && resultCode == Activity.RESULT_OK) {
            curPage = 1
            getDataList()
        }
    }

    //    初始化刷新控件
    private fun initRefreshLayout() {
        smartLayout.setOnRefreshListener {
            curPage = 1
            getDataList()
            smartLayout.setEnableLoadMore(true)

        }
        smartLayout.setOnLoadMoreListener {
            getDataList()
        }
    }

    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        mAdapter = PTeacherFragmentAdapter(dataList, Box.context)
        rv_list.adapter = mAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)
        mAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == ITEM_CLICK) {//
                var bundle = Bundle()
                bundle.putSerializable("objectId",obj.id)//
                UIHelper.jump(activity, PCourseDetailActivity::class.java,bundle)
            }
        }
        //模拟数据
       /* if (mAdapter.itemCount == 0) {
            var lists: MutableList<String> = mutableListOf("","")
            dataList.addAll(lists)
            mAdapter.notifyDataSetChanged()
        }*/
    }
    private fun getDataList() {
//        Alert.loading(context)
        stopRefresh()

        ApiClient.api.familyeduAppoint(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    dataList.clear()
                    /*if (curPage == 1) {
                        dataList.clear()
                        if (dataList.size == 0) {
                            multiView.showEmpty()
                        }
                    }*/
                    if (it.size <= 0) {
                        smartLayout.setEnableLoadMore(false)
                        multiView.showEmpty()
                        tv_hint.visibility=View.GONE
                    } else {
                        dataList.addAll(it)
                        mAdapter.notifyDataSetChanged()
                        multiView.showContent()
                        smartLayout.setEnableLoadMore(false)
                        tv_hint.visibility=View.VISIBLE
                    }
                }
                _onError {
                    Alert.close()
                    if (ErrorHandler.handle(it).errorMsg == "缺失token参数"||
                        ErrorHandler.handle(it).errorMsg=="获取登录信息失败,请重新登陆"||
                        ErrorHandler.handle(it).errorMsg=="你的登录已失效,请重新登录") {
                        ShowToast("登录信息已失效，请重新登录")
                        UIHelper.jumpForResult(activity, LoginActivity::class.java,103)
                        return@_onError
                    }
                    tv_hint.visibility=View.GONE
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }
    }

    private fun stopRefresh() {
        if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }
    }


    override fun onClick(v: View?) {
//        UserCache.token=""
        if (TextUtils.isEmpty(UserCache.token)) {
            UIHelper.jumpForResult(activity, LoginActivity::class.java,103)
            return
        }
        when (v?.id) {
            R.id.tb_onoff->{
                if (tb_onoff.isToggleOn) {
                    setIfJiajiao("0")
                } else {
                    setIfJiajiao("1")
                }


            }
            R.id.tv_notice -> {//通知列表
                context.startActivity_ex<NoticeActivity>()
            }
            R.id.tv_attent ->{//教师租赁
//                context.startActivity_ex<AttendenceActivity>()
            }
            R.id.tv_appro ->{//招聘
//                context.startActivity_ex<MyApprovalActivity>()

            }

            R.id.tv_perfect ->{//完善家教信息
//                UIHelper.jump(context,PManagerInfoActivity::class.java)///完善家教信息
                UIHelper.jump(activity, PManagerActivity::class.java)//家教管理
            }

        }
    }



    private fun setIfJiajiao(ifJiajiao: String) {
        Alert.loading(context)
        //ifJiajiao":"",//家教中是否招募学生：0、代表不招募；1、代表招聘
        stopRefresh()
        ApiClient.api.setIfJiajiao(ifJiajiao,UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    //家教中是否招募学生：0、代表关闭招募；1、代表开启招聘
                    if (ifJiajiao == "0") {
                        tb_onoff.toggleOff()
                    } else if (ifJiajiao == "1") {
                        tb_onoff.toggleOn()
                    }
                    ShowToast("提交成功")
                    getUserInfos()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }
    override fun closeMvp() {
    }
}